package main

import (
	"flag"
	"gitee.com/yysf_xin/dplog/pkg/extracter/fex"
	"gitee.com/yysf_xin/dplog/pkg/extracter/java"
	"gitee.com/yysf_xin/dplog/pkg/index"
	"gitee.com/yysf_xin/dplog/pkg/index/gse"
	"gitee.com/yysf_xin/dplog/pkg/slog"
	"gitee.com/yysf_xin/go-common/tools"
	"github.com/blevesearch/bleve/v2"
	_ "github.com/blevesearch/bleve/v2"
	"github.com/blevesearch/bleve/v2/document"
	"log"
	"net/http"
	_ "net/http/pprof"
	"os"
	"time"
)

func Search(idx bleve.Index, s string) {
	query := bleve.NewMatchQuery(s)
	query.Analyzer = gse.TokenName
	search := bleve.NewSearchRequest(query)
	searchResults, err := idx.Search(search)

	if err != nil {
		panic(err)
	}
	println("search", s, searchResults.String())

	for _, v := range searchResults.Hits {
		d, err := idx.Document(v.ID)
		if err != nil {
			log.Println(err)
			continue
		}
		if doc, ok := d.(*document.Document); ok {
			for _, v := range doc.Fields {
				println(v.Name(), tools.BytesToString(v.Value()))
			}
		}
		println(d)
	}

}

var (
	Opt  index.SearchOpt
	Java java.Opt
	Log  slog.Option
	File string
)

func main() {
	flag.StringVar(&File, "f", "", "use slog file")
	flag.StringVar(&Opt.Dir, "dir", "idx", "search file index dir")
	flag.StringVar(&Opt.Dict, "dict", "dict/dict.bin", "jiba dict files")
	flag.StringVar(&Opt.Analyzer, "analyzer", gse.TokenName, "search text analyzer")
	flag.StringVar(&Opt.Keyword, "k", "", "search keyword")
	java.InitFlag(&Java)
	slog.InitFlag(&Log)

	flag.Parse()

	if Opt.Dir == "" {
		println("idx is empty")
		os.Exit(0)
	}

	go http.ListenAndServe("127.0.0.1:9999", nil)

	em, err := index.NewSaver(&Opt)

	if err != nil {
		panic(err)
	}

	defer func() {
		err = em.Idx.Close()
		if err != nil {
			log.Println(err)
		}
	}()

	c := slog.NewCollect(&Log, fex.NewMakeLog(&Java, "test"), em)

	if File != "" {
		r, err := slog.NewFileReader(File, c)

		if err != nil {
			panic(err)
		}

		defer r.Close()

		now := time.Now()
		r.Run()

		log.Println("read file take", time.Now().Sub(now).String())
	}

	_ = c

	log.Println("end")

	if Opt.Keyword != "" {
		Search(em.Idx, Opt.Keyword)
	}

	//var k = []string{"抽奖","INFO","红包","丰享"}
	//
	//for _,v := range k {
	//	Search(em.Idx,v)
	//}
}
